package com.rr.learningdemo.flink;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * @author RR
 * @date 2021/6/6 22:55
 */
public class WordCountDataStream {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        //从txt文件读取数据
        String txtFilePath = "G:\\IDEAProject\\learning-demo\\src\\main\\resources\\WordCount.txt";
//        DataStream<String> dataStreamSource = env.readTextFile(txtFilePath);

        //从nc那里读取，搞个虚拟机，然后执行nc -lk 3306
        DataStream<String> dataStreamSource = env.socketTextStream("172.16.5.33", 3306);

        //这里flatMap之后，得到一个什么SingleOutputStreamOperation，其实它也是一个DataStream，它的泛型就是我们的flatMap指定的
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = dataStreamSource.flatMap(new MyFlatMapper())
                .filter(new MyFilterFunction())
                //fields这里如果tuple类型，可以用012，如果是具体什么类，
                //可以用字段名（例如"id"）或者lambda(o->o.getId())这样来做keyBy
                .keyBy(0)
                .timeWindow(Time.seconds(5))
                .sum(1);

        sum.print();

        //执行任务
        env.execute();
    }

    //将文本内容按空格，将单词分隔出来，然后按照（word，1）的形式返回
    //这里的flatMapFunction有两个泛型，第一个String，是接收的数据的泛型，后面的Tuple2是我们输出的结果的泛型
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String,Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector){
            String[] words = s.split(" ");
            for (String word : words) {
                collector.collect(new Tuple2<>(word, 1));
            }
        }
    }

    //定义一个过滤，当是hehe的时候就不要了
    public static class MyFilterFunction implements FilterFunction<Tuple2<String, Integer>> {
        @Override
        public boolean filter(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
            return !stringIntegerTuple2.f0.equals("hehe");
        }
    }
}
